package cn.edu.gdut.deepcode.component;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class GlobalIdGenerator {
    public static final Long START_TIME= TimeUnit.DAYS.toMillis((2025-1970)*365);

    @Autowired
    private final StringRedisTemplate redisTemplate;
    public Long generate(String key){

        Long count = redisTemplate.opsForValue().increment(key);
        if (count==null){
            throw new RuntimeException("id生成错误");
        }
        long timeStamp=System.currentTimeMillis()-START_TIME;
        return (timeStamp<<16)|count;
    }
}
